package com.weapp.system.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.weapp.common.utils.JWTUtil;
import com.weapp.common.utils.RedisUtils;
import com.weapp.system.constant.CacheConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jsy
 * @description: 第三方登陆拦截器
 * @date 2022/7/12 15:49
 */
public class JWTLoginInterceptor implements HandlerInterceptor {

  @Autowired
  private RedisUtils redisUtils;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    throws Exception {
    // token拦截处理
    String token = request.getHeader("token");
    // 如果集成redis中间件，务必要在redis里面进行同步比对校验
    if (token != null && JWTUtil.validate(token)) {
      String userId = JWTUtil.parseJWT(token);
      if (ObjectUtil.isNotNull(redisUtils.get(CacheConstants.LOGIN_TOKEN_KEY + userId))) {
        return true;
      } else {
        response.getWriter().write("非法参数请求");
        response.flushBuffer();
        return false;
      }
    } else {
      response.getWriter().write("非法参数请求");
      response.flushBuffer();
      return false;
    }
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                         ModelAndView modelAndView) throws Exception {

  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
    throws Exception {

  }
}
